package com.sdh.onlinemarket.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdh.onlinemarket.common.annotation.AdminToken;
import com.sdh.onlinemarket.common.annotation.UserLoginToken;
import com.sdh.onlinemarket.common.dto.ManagerOrderDTO;
import com.sdh.onlinemarket.common.dto.OrderInfoDTO;
import com.sdh.onlinemarket.common.dto.OrderListDTO;
import com.sdh.onlinemarket.common.lang.Result;
import com.sdh.onlinemarket.common.util.OrderUtil;
import com.sdh.onlinemarket.entity.*;
import com.sdh.onlinemarket.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 施德昊
 * @since 2021-11-22
 */
@Api(tags = "订单相关模块")
@RestController
@RequestMapping("/orders")
@Slf4j
public class OrdersController {

    @Autowired
    private ShopcardService shopcardService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private OrderlistService orderlistService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private UserService userService;
    @Autowired
    private PaymentFlowService paymentFlowService;

    @UserLoginToken
    @ApiOperation(value = "添加新订单")
    @PostMapping("/setorders")
    @ResponseBody
    public Result setOrders(String userid){
        if(userid==null){
            return Result.fail("param error");
        }

        List<Shopcard> shopcardList = shopcardService.list(new QueryWrapper<Shopcard>().eq("userid",userid));
        User user = userService.getOne(new QueryWrapper<User>().eq("userid",userid));
        String orderid = OrderUtil.getOrderCode(user.getId());
        Orders orders = new Orders();
        orders.setOrderid(orderid);
        orders.setUserid(userid);
        orders.setOstatus(0);
        float totalPrice = 0;

        if(shopcardList.size() == 0){
            return Result.fail("购物车内没有商品");
        }
        for (Shopcard shopcardtemp:shopcardList) {
            Item itemtemp = itemService.getOne(new QueryWrapper<Item>().eq("itemid",shopcardtemp.getItemid()));
            Orderlist orderlist = new Orderlist();
            orderlist.setOrderid(orderid);
            orderlist.setItemid(shopcardtemp.getItemid());
            orderlist.setInum(shopcardtemp.getInum());
            orderlistService.save(orderlist);
            if (itemtemp != null){
                totalPrice += itemtemp.getIprice()*shopcardtemp.getInum();
            }
        }
        orders.setTprice(BigDecimal.valueOf(totalPrice));
        ordersService.save(orders);
        shopcardService.updateStorage(userid);
        shopcardService.remove(new QueryWrapper<Shopcard>().eq("userid",userid));
        log.info("添加新商品"+orderid);
        return Result.succ("success",orderid);
    }

    @UserLoginToken
    @ApiOperation(value = "获取当前用户的订单")
    @PostMapping("/getorders")
    @ResponseBody
    public Result getOrders(String userid){
        List<OrderInfoDTO> orderInfoDTOList = new ArrayList<>();
        OrderInfoDTO orderInfoDTOtemp;
        List<OrderListDTO> orderListDTOListtemp;
        OrderListDTO orderListDTOtemp;
        List<Orders> ordersList = ordersService.list(new QueryWrapper<Orders>().eq("userid",userid).orderByDesc("ordertime"));
        if (ordersList.size() == 0){
            return Result.fail("user order not found");
        }
        for (Orders ordertemp:ordersList) {
//            复制订单属性
            orderInfoDTOtemp = new OrderInfoDTO();
            BeanUtils.copyProperties(ordertemp,orderInfoDTOtemp);
            switch (ordertemp.getOstatus()){
                case 0 :{
                    orderInfoDTOtemp.setStatusOfString("未支付");
                    break;
                }
                case 1 :{
                    orderInfoDTOtemp.setStatusOfString("已付款");
                    break;
                    }
                case 2 :{
                    orderInfoDTOtemp.setStatusOfString("已发货");
                    break;
                    }
                case 3 :{
                    orderInfoDTOtemp.setStatusOfString("已完成");
                    break;
                    }
            }

            System.out.println(orderInfoDTOtemp);
//            获取商品信息
            List<Orderlist> orderlistList = orderlistService.list(new QueryWrapper<Orderlist>().eq("orderid",ordertemp.getOrderid()));
            orderListDTOListtemp = new ArrayList<>();
//            复制订单内商品信息
            for (Orderlist orderlisttemp:orderlistList) {
                orderListDTOtemp = new OrderListDTO();
                orderListDTOtemp.setInum(orderlisttemp.getInum());
                Item item = itemService.getOne(new QueryWrapper<Item>().eq("itemid",orderlisttemp.getItemid()));
                if(item == null){
                    item = new Item();
                    item.setItemname("商品已被清除");
                    item.setIdescrip("商品已被清除");
                    item.setIprice((float) 0);
                }
                BeanUtils.copyProperties(item,orderListDTOtemp);
                orderListDTOListtemp.add(orderListDTOtemp);
            }
            orderInfoDTOtemp.setOrderlists(orderListDTOListtemp);
            orderInfoDTOList.add(orderInfoDTOtemp);
        }
        return Result.succ("success",orderInfoDTOList);
    }

    @UserLoginToken
    @ApiOperation(value = "取消订单",notes="未付款前可以取消")
    @PostMapping("/cancelorder")
    @ResponseBody
    public Result cancelOrder(String orderid){
        Orders orderstemp = ordersService.getOne(new QueryWrapper<Orders>().eq("orderid",orderid));
        if(orderstemp == null){
            return Result.fail("order not found");
        }else {
            //当订单不处于未支付状态时(如已支付，已发货等)，暂不支持退款
            log.info("取消订单"+orderid);
            if(orderstemp.getOstatus()!=0){
                return Result.fail("已付款的订单不支持取消");
            }else {
                orderstemp.setOstatus(-1);
                ordersService.update(orderstemp, new QueryWrapper<Orders>().eq("orderid", orderstemp.getOrderid()));
                return Result.succ("成功取消");
            }
        }

    }

    @UserLoginToken
    @ApiOperation(value = "获取一个订单的详细信息")
    @PostMapping("/getoneorder")
    @ResponseBody
    public Result getOneOrder(String orderid){
        Orders orders = ordersService.getOne(new QueryWrapper<Orders>().eq("orderid",orderid));
        OrderInfoDTO orderInfoDTO = new OrderInfoDTO();
        if (orders != null ) {
            if(orders.getOstatus()>=0){
                List<Orderlist> orderlists = orderlistService.list(new QueryWrapper<Orderlist>().eq("orderid",orderid));
                BeanUtils.copyProperties(orders,orderInfoDTO);

                switch (orders.getOstatus()){
                    case 0 :{
                        orderInfoDTO.setStatusOfString("未支付");
                        break;
                    }
                    case 1 :{
                        orderInfoDTO.setStatusOfString("已付款");
                        break;
                    }
                    case 2 :{
                        orderInfoDTO.setStatusOfString("已发货");
                        break;
                    }
                    case 3 :{
                        orderInfoDTO.setStatusOfString("已完成");
                        break;
                    }
                }

                List<OrderListDTO> orderListDTOListtemp = new ArrayList<>();
//            复制订单内商品信息
                for (Orderlist orderlisttemp:orderlists) {
                    OrderListDTO orderListDTOtemp = new OrderListDTO();
                    orderListDTOtemp.setInum(orderlisttemp.getInum());
                    Item item = itemService.getOne(new QueryWrapper<Item>().eq("itemid",orderlisttemp.getItemid()));
                    if(item == null){
                        item = new Item();
                        item.setItemname("商品已被清除");
                        item.setIdescrip("商品已被清除");
                        item.setIprice((float) 0);
                    }
                    BeanUtils.copyProperties(item,orderListDTOtemp);
                    System.out.println(orderListDTOtemp);
                    orderListDTOListtemp.add(orderListDTOtemp);
                }
                orderInfoDTO.setOrderlists(orderListDTOListtemp);
                System.out.println(orderInfoDTO);
                return Result.succ("success",orderInfoDTO);
            }else {
                return Result.fail("order not found");
            }
        }else {
            return Result.fail("order not found");
        }
    }


    @AdminToken
    @ApiOperation(value = "管理员获取订单列表")
    @PostMapping("/managerorder")
    @ResponseBody
    public Result managerOrder(){
//        List<OrderInfoDTO> orderInfoDTOList = new ArrayList<>();
//        OrderInfoDTO orderInfoDTOtemp;
        List<OrderListDTO> orderListDTOListtemp;
        OrderListDTO orderListDTOtemp;
        ManagerOrderDTO managerOrderDTOtemp;
        List<ManagerOrderDTO> managerOrderDTOList = new ArrayList<>();
        List<Orders> ordersList = ordersService.list(new QueryWrapper<Orders>().orderByDesc("ordertime"));
        if (ordersList.size() == 0){
            return Result.fail("there is no order");
        }
        for (Orders ordertemp:ordersList) {
//            复制订单属性
            managerOrderDTOtemp = new ManagerOrderDTO();

            BeanUtils.copyProperties(ordertemp,managerOrderDTOtemp);
            if(managerOrderDTOtemp.getUserid() == null){
                return Result.fail("unknown error");
            }
            User userTemp = userService.getOne(new QueryWrapper<User>().eq("userid",managerOrderDTOtemp.getUserid()));
            BeanUtils.copyProperties(userTemp,managerOrderDTOtemp);

            System.out.println(managerOrderDTOtemp);
            switch (ordertemp.getOstatus()){
                case 0 :{
                    managerOrderDTOtemp.setStatusOfString("未支付");
                    break;
                }
                case 1 :{
                    managerOrderDTOtemp.setStatusOfString("已付款");
                    break;
                }
                case 2 :{
                    managerOrderDTOtemp.setStatusOfString("已发货");
                    break;
                }
                case 3 :{
                    managerOrderDTOtemp.setStatusOfString("已完成");
                    break;
                }
            }
            System.out.println(managerOrderDTOtemp);

//            获取商品信息
            List<Orderlist> orderlistList = orderlistService.list(new QueryWrapper<Orderlist>().eq("orderid",ordertemp.getOrderid()));
            orderListDTOListtemp = new ArrayList<>();
//            复制订单内商品信息

            for (Orderlist orderlisttemp:orderlistList) {
                orderListDTOtemp = new OrderListDTO();
                orderListDTOtemp.setInum(orderlisttemp.getInum());
                Item item = itemService.getOne(new QueryWrapper<Item>().eq("itemid",orderlisttemp.getItemid()));
                if(item == null){
                    item = new Item();
                    item.setItemname("商品已被清除");
                    item.setIdescrip("商品已被清除");
                    item.setIprice((float) 0);
                }
                BeanUtils.copyProperties(item,orderListDTOtemp);
                orderListDTOListtemp.add(orderListDTOtemp);
            }
            managerOrderDTOtemp.setOrderlists(orderListDTOListtemp);
            managerOrderDTOList.add(managerOrderDTOtemp);
        }
        return Result.succ("success",managerOrderDTOList);
    }

    @AdminToken
    @ApiOperation(value = "订单发货")
    @PostMapping("/orderpost")
    @ResponseBody
    public Result orderPost(String orderid,String postid){
        Orders orders = ordersService.getOne(new QueryWrapper<Orders>().eq("orderid",orderid));
        if (orders == null){
            return Result.fail("未找到订单");
        }
        if(postid == null){
            return Result.fail("快递单号不存在");
        }
        if(orders.getPostid()!=null){
            return Result.fail("已处于发货状态中");
        }
        if (orders.getOstatus()<1){
            return Result.fail("订单状态不正确");
        }
        orders.setOstatus(2);
        orders.setPostid(postid);
        ordersService.update(orders,new QueryWrapper<Orders>().eq("orderid",orderid));
        return Result.succ("成功发货");
    }

    @AdminToken
    @ApiOperation(value = "快递单号修改")
    @PostMapping("/postmodify")
    @ResponseBody
    public Result postModify(String orderid,String postid){
        Orders orders = ordersService.getOne(new QueryWrapper<Orders>().eq("orderid",orderid));
        if (orders == null){
            return Result.fail("未找到订单");
        }
        if(postid == null){
            return Result.fail("快递单号不存在");
        }
        if(orders.getPostid()==null){
            return Result.fail("请先发货");
        }
        orders.setPostid(postid);
        ordersService.update(orders,new QueryWrapper<Orders>().eq("orderid",orderid));
        return Result.succ("修改成功");
    }

    @UserLoginToken
    @ApiOperation(value = "订单完成")
    @PostMapping("/orderfin")
    @ResponseBody
    public Result orderFin(String orderid){
        Orders orders = ordersService.getOne(new QueryWrapper<Orders>().eq("orderid",orderid));
        if (orders == null){
            return Result.fail("未找到订单");
        }
        if (orders.getOstatus()<2){
            return Result.fail("订单状态不正确");
        }
        orders.setOstatus(3);
        ordersService.update(orders,new QueryWrapper<Orders>().eq("orderid",orderid));
        return Result.succ("订单已完成");
    }

    @UserLoginToken
    @ApiOperation(value = "获取当前订单的快递单号")
    @GetMapping("/getpostid")
    @ResponseBody
    public Result getPostId(String orderid){
        if (orderid == null) {
            return Result.fail("订单id不存在");
        }
        Orders orders = ordersService.getOne(new QueryWrapper<Orders>().eq("orderid",orderid));
        if (orders == null) {
            return Result.fail("订单不存在");
        }
         if (orders.getOstatus()!=2) {
            return Result.fail("订单状态不正确");
        }
        return Result.succ(orders.getPostid());
    }

    @UserLoginToken
    @ApiOperation(value = "查询支付状态")
    @GetMapping("/querystatus")
    @ResponseBody
    public Result queryStatus(String orderid) {
        if (orderid == null) {
            return Result.fail("参数错误");
        }
        Orders orders = ordersService.getOne(new QueryWrapper<Orders>().eq("orderid", orderid));
        if (orders == null) {
            return Result.fail("订单不存在");
        }
        PaymentFlow paymentFlow = paymentFlowService.getOne(new QueryWrapper<PaymentFlow>().eq("orderid", orderid));
        if (paymentFlow == null) {
            return Result.fail("支付异常");
        }
        if (orders.getOstatus() >= 1) {
            return Result.succ("已支付");
        } else if (orders.getOstatus() == 0) {
            return Result.succ("未支付");
        } else {
            return Result.succ("订单状态异常");
        }
    }
}
